package com.android.lovingpet.common;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;

import com.android.lovingpet.bean.JsonPost;
import com.android.lovingpet.bean.Post;
import com.android.lovingpet.util.CallbackStore;
import com.android.lovingpet.util.MyHttp;
import com.android.lovingpet.util.URLStore;
import com.android.lovingpet.util.Utility;
import com.google.gson.Gson;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class PostModel {

    private volatile static PostModel instance;
    private PostModel() {}
    public static PostModel getInstance() {
        if (instance == null) {
            synchronized (PostModel.class) {
                if (instance == null) {
                    instance = new PostModel();
                }
            }
        }
        return instance;
    }

    public void upload(int id, int userType, int albumType, List<File> album, Back back) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("id", id + "");
        builder.addFormDataPart("userType", userType + "");
        builder.addFormDataPart("albumType", albumType + "");
        for (File file : album) {
            builder.addFormDataPart("album", file.getName(),
                    RequestBody.create(MediaType.parse("application/octet-stream"), file));
        }
        new OkHttpClient().newCall(new Request.Builder()
                .addHeader("cookie", Utility.getJSessionId())
                .post(builder.build())
                .url(URLStore.ALBUM_UPLOAD)
                .build()).enqueue(new CallbackStore.CallbackNon<>(back));
    }

    /**
     * @param context 300字以内
     * @param type 0：寄主对寄养家庭的评价，1：美宠秀秀；2，养宠心得；3，相约遛宠；4，宠物小帮手
     * @param targetId 动态/评价：0；评论：被评论的动态的id
     * @param postType 0，动态；1，评论；2，寄主对寄养家庭的评价（目前postType为2不可用）
     * @param evaluationType 寄主对寄养家庭的评价，0，差评；1，好评（仅当postType为2的时候才需要这个参数）
     * @param anonymous 0，否；1，是（仅当postType为2的时候才需要这个参数）
     * @param hostId 寄养家庭的id（仅当postType为2的时候才需要这个参数）
     */
    public void post(String context, int type, int targetId, int postType, Integer evaluationType, Integer anonymous, Integer hostId, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("context", context);
        params.put("type", type + "");
        params.put("targetId", targetId + "");
        params.put("postType", postType + "");
        if (evaluationType != null) {
            params.put("evaluationType", evaluationType + "");
        }
        if (anonymous != null) {
            params.put("anonymous", anonymous + "");
        }
        if (hostId != null) {
            params.put("hostId", hostId + "");
        }
        MyHttp.getInstance().postAsync(Utility.getJSessionId(), URLStore.POST_ADD, params, new CallbackStore.CallbackId<>(back));
    }

    public void deletePost(int id, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id + "");
        MyHttp.getInstance().postAsync(Utility.getJSessionId(), URLStore.POST_DELETE, params, new CallbackStore.CallbackNon<>(back));
    }

    /**
     * 仅当postType为2时有valuation字符串
     * @param postType postType:0,动态；1，评论；2，对寄养家庭的评价
     */
    public void getPost(int id, int postType, int userType, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id + "");
        params.put("postType", postType + "");
        MyHttp.getInstance().postAsync(Utility.getJSessionId(), URLStore.POST_GET, params, new CallbackStore.CallbackImpl<Back>(back) {
            @Override
            public void onResponse(String json) {
                JsonPost jsonPost = new Gson().fromJson(json, JsonPost.class);
                Post post = jsonPost.getPost();
                if (post.getAlbumCount() > 0) {
                    FileModel.getInstance().downloadAlbum(post.getRealId(), userType, 0, new FileModel.AlbumBack() {
                        @Override
                        public void loadSuccess(List<String> images) {
                            post.setImages(images);
                            Bundle bundle = new Bundle();
                            bundle.putParcelable("post", post);
                            back.onSuccess(bundle);
                        }

                        @Override
                        public void onFailure(String msg) {
                            back.onFailure(msg);
                        }

                        @Override
                        public void onSuccess(@Nullable Bundle bundle) {

                        }
                    });
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("post", post);
                    back.onSuccess(bundle);
                }
            }
        });
    }

    /**
     * @param type 0，寄养家庭的评价；1，美宠秀秀；2，养宠心得；3，相约遛宠；4，宠物小帮手；5，个人动态
     * @param postType 0，社区动态；1，评论 ；2，对寄养家庭的评价；3，个人动态（宠物日记）
     * @param chooseType （只有当postType为0或3时需要此参数）：0，获得全部符合条件的动态；1，获得关注人的符合条件的动态；
     */
    public void getIdsByType(int type, int postType, int offset, int num, Integer chooseType, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("type", type + "");
        params.put("postType", postType + "");
        params.put("offset", offset + 1 + "");
        params.put("num", num + "");
        if (chooseType != null) {
            params.put("chooseType", chooseType + "");
        }
        MyHttp.getInstance().postAsync(Utility.getJSessionId(), URLStore.POST_GET_BY_TYPE, params, new CallbackStore.CallbackIds<>(back));
    }

    public void getIdsByUser(int userId, int postType, int offset, int num, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("userId", userId + "");
        params.put("postType", postType + "");
        params.put("offset", offset + 1 + "");
        params.put("num", num + "");
        MyHttp.getInstance().postAsync(Utility.getJSessionId(), URLStore.POST_GET_BY_USER, params, new CallbackStore.CallbackIds<>(back));
    }

    public void getIdsByPost(int targetId, int offset, int num, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("targetId", targetId + "");
        params.put("offset", offset + 1 + "");
        params.put("num", num + "");
        MyHttp.getInstance().postAsync(Utility.getJSessionId(), URLStore.POST_GET_BY_POST, params, new CallbackStore.CallbackIds<>(back));
    }
}
